package com.yunxin.core.application.service.impl;

import cn.hutool.core.text.CharSequenceUtil;
import com.fasterxml.jackson.core.type.TypeReference;
import com.yunxin.common.exception.BusinessException;
import com.yunxin.common.utils.JacksonUtils;
import com.yunxin.core.application.assembler.PageDataAssembler;
import com.yunxin.core.application.dto.page.PageComponentElementInfoDataDTO;
import com.yunxin.core.application.dto.page.PageInfoDataDTO;
import com.yunxin.core.application.service.PageQueryGatewayService;
import com.yunxin.core.domain.external.product.ProductExternalService;
import com.yunxin.core.infra.common.page.enums.PgeCacheStatusEnum;
import com.yunxin.core.infra.persistence.mapper.page.PageCacheExtendMapper;
import com.yunxin.core.infra.persistence.mapper.page.PagePopupUserRecordExtendMapper;
import com.yunxin.core.utils.infra.common.constant.CoreResultCode;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

/**
 * @author zero°
 * @since 2023-05-31
 */
@Service
@RequiredArgsConstructor
public class PageQueryGatewayServiceImpl implements PageQueryGatewayService {

    private final PageCacheExtendMapper pageCacheExtendMapper;

    private final PagePopupUserRecordExtendMapper pagePopupUserRecordExtendMapper;

    private final ProductExternalService productExternalService;

    @Override
    public PageInfoDataDTO<PageComponentElementInfoDataDTO> getPageConfig(String pageCode ,String userCode) {
        String pageData = pageCacheExtendMapper.getLastPageCache(pageCode, PgeCacheStatusEnum.PUBLISHED.getValue());
        if (CharSequenceUtil.isEmpty(pageData)) {
            throw new BusinessException(CoreResultCode.PAGE_NOT_EXIST);
        }
        PageInfoDataDTO pageConfig = JacksonUtils.X.parse(pageData, new TypeReference<PageInfoDataDTO<PageComponentElementInfoDataDTO>>() {});
        PageDataAssembler.X.dealGatewayPageConfigInfoDTO(pageConfig, userCode, pagePopupUserRecordExtendMapper, productExternalService);
        return pageConfig;
    }
}
